/**
 * 0. Project	: com.dnbns.bodywater 프로젝트
 *
 * 1. FileName	: MapActivity.java
 * 2. Package	: com.dnbns.bodywater
 * 3. 작성자		: 윤화현
 * 4. 작성일		: 2013. 11. 21. 오전 9:23:02
 * 5. Comment	: 
 */

package com.dnbns.bodywater;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.dnbns.bodywater.bean.MapBean;
import com.dnbns.common.CommonAsyncTask;
import com.dnbns.common.StaticValue;
import com.dnbns.network.NetworkChecker;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapActivity extends FragmentActivity {

	GoogleMap mGoogleMap;
	private boolean serverFlag = false;
	private ArrayList<MapBean> mList;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map);
		
		init();
		initTop();
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		getWaterData();
	}
	
/**
 ***************************************************************
 * init
 ***************************************************************
 */
	
	private void init(){

		GooglePlayServicesUtil.isGooglePlayServicesAvailable(MapActivity.this);
		
		final View mapView = getSupportFragmentManager().findFragmentById(R.id.map).getView();
		if (mapView.getViewTreeObserver().isAlive()) {
	        mapView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
	            @SuppressWarnings("deprecation")
				@SuppressLint("NewApi")
	            // We check which build version we are using.
	            @Override
	            public void onGlobalLayout() {
	                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
	                    mapView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
	                } else {
	                    mapView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
	                }
	                // Send notification that map-loading has completed.
	                onMapFinishedLoading();
	            }
	        });
	    }
	}

	private void initTop(){
		ImageView back = (ImageView)findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}
	
	//맵 로딩 끝.
	protected void onMapFinishedLoading() {
		mGoogleMap = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
		
		//줌 금지.
		mGoogleMap.getUiSettings().setZoomGesturesEnabled(false);
		mGoogleMap.getUiSettings().setZoomControlsEnabled(false);
		
		LatLng position = new LatLng(35.960223,127.691345);
		//맵 위치이동.
		mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 3));
		
		//마커 클릭 리스너
		mGoogleMap.setOnMarkerClickListener(new OnMarkerClickListener() {
			
			@Override
			public boolean onMarkerClick(Marker marker) {
				// TODO Auto-generated method stub
				
				return false;
			}
		});
	}
	
	private void onMapMarker(){
		TextView map_txt = (TextView)findViewById(R.id.map_txt);

		double drink = 0;
		for(int i=0; i<mList.size(); i++){
			LatLng position = new LatLng(mList.get(i).getLat(), mList.get(i).getLng());

			Bitmap mImg = BitmapFactory.decodeResource(getResources(), R.drawable.map_img);
			BitmapDescriptor mBitmap = BitmapDescriptorFactory.fromBitmap(mImg);
			
			drink += mList.get(i).getSums();
			//마커 설정.
			Marker melbourne = mGoogleMap.addMarker(new MarkerOptions()
						.position(position)
						.icon(mBitmap)
						.title(mList.get(i).getSums()+"ml")
					);
			
			melbourne.showInfoWindow();
		}
		
		map_txt.setText("All : "+drink+"ml");

	}

/**
 * =================================================================================
 * 서버연동
 * =================================================================================
 */

	private void getWaterData() {
		
		if(serverFlag){
			return;
		}
		
		serverFlag = true;
		
		NetworkChecker nc = new NetworkChecker();
		if(!nc.isUseNetwork(getApplicationContext(), this)){
			return;
		}

		JSONObject json = new JSONObject();
		try {
			json.put("url", StaticValue.URL+StaticValue.FR_2002);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		mList = new ArrayList<MapBean>();
		
		//서버통신
		CommonAsyncTask.getInstance(getApplicationContext(), mHandler).getMapDataTask(json, mList);
	}

/**
 * =================================================================================
 * Handler
 * =================================================================================
 */

	@SuppressLint("HandlerLeak")
	public Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			//서버전송완료
			case 1:
				onMapMarker();
				serverFlag = false;
				break;
			//서버전송실패
			case 9999:
				serverFlag = false;
				break;
			}
		}
	};

}
